﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Data.OleDb;
using GoldenAgeHelper.DAL;
using GoldenAgeHelper.db;
using GoldenAgeHelper.globel;
using GoldenAgeHelper.common;
using System.Threading;
using System.IO;
using Fycayy.Common;
using System.Runtime.Serialization.Formatters.Binary;

namespace GoldenAgeHelper
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        int starttime = 0;/*每次跑商所用的时间*/
        int begintime = 0;/*程序所运行的时间*/
        int lvyoutime = 0;/*每次跑地图所用的时间*/
        int numtime = 0;/*计时器的当前剩余时间*/

        int errornum = 0;
        List<string> lstError = new List<string>();

        string sids, snames, surls;/*服务器地址，名称，URL*/
        string defaulttitle;/*默认标题，设置标题*/
        private DateTime lastGrarden;/*最后一次拾取花园金钱的时间*/



        #region GoldenAge线程
        Thread tGALogin;
        Thread tGAPS;
        Thread tGAAtta;
        Thread tGAstart;
        Thread tGAFB;
        Thread test;
        Thread tGAJJ;
        Thread tGAAuto;
        Thread tGATemp;
        Thread tGAJineng;
        Thread tGASearchFor;
        #endregion

        DataTable envidt;
        public delegate void DelInvoke();
        public delegate void DelTimerC(int time);
        public delegate void DelTimeS(bool state);
        public delegate void DelSetinfo(string info);
        public delegate void DelShowMsg(string msg);


        IniFiles ini = null;
        IniFiles sys = null;

        #region 窗体注册事件

        private void Form1_Load(object sender, EventArgs e)
        {
            defaulttitle = this.Text;

            //注册事件
            GA.EveMSG += new GA.DelShowMsg(AddMessage);
            GA.EveInfo += new GA.DelSetinfo(SetInfo);
            GA.EveTimeC += new GA.DelTimerC(SetTimes);
            GA.EveTimeS += new GA.DelTimeS(SetTimerState);

            //double d1 = Math.Sqrt(34)*1000 / 736;
            //double d2 = Math.Sqrt(122)*1000 / 1395;
            //MessageBox.Show(d1+"_"+d2);
            ////0.250

            //使用线程启动，异步加载内容
            tGAstart = new Thread(new ThreadStart(delegate()
            {
                try
                {
                    AddMessage("程序已经启动，加载配置文件...");
                    ini = new IniFiles("config/user.ini");
                    sys = new IniFiles("config/sys.ini");
                    AddMessage("正在加载城市配置...");
                    #region 加载城市配置文件
                    //MessageBox.Show(sys.ReadString("sys","src","nlll"));
                    Database.Connect(DBType.Access, @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sys.ReadString("sys", "src", "citis.mdb") + ";");
                    Dictionary<int, string> citis = City.GetAllCity();
                    this.Invoke(new DelInvoke(delegate()
                    {

                        foreach (int s in citis.Keys)
                        {
                            CboItem item = new CboItem();
                            item.Key = s;
                            item.Value = citis[s];

                            this.cboline1.Items.Add(item);
                            this.cboline2.Items.Add(item);
                            this.cboline3.Items.Add(item);
                            this.cboFindCity.Items.Add(item);
                            this.cboJJlookfor.Items.Add(item);
                        }

                        this.cboline1.SelectedItem = new CboItem(City.GetCityID("楚州"), "楚州");
                        this.cboline2.SelectedItem = new CboItem(City.GetCityID("徐州"), "徐州");
                    }));
                    #endregion
                    sids = sys.ReadString("server", "id", "10001");
                    surls = sys.ReadString("server", "url", "http://t1.nexttime.cn");
                    snames = sys.ReadString("server", "name", "玉门关一服");
                    for (int i = 0; i < sids.Split(',').Length; i++)
                    {
                        CboItem item = new CboItem(Convert.ToInt32(sids.Split(',')[i]), snames.Split(',')[i]);
                        this.Invoke(new DelInvoke(delegate()
                        {
                            this.cboServer.Items.Add(item);
                            //this.cboServer.Items.Add(new System.Web.UI.WebControls.ListItem(snames.Split(',')[i], sids.Split(',')[i]));
                        }));
                    }
                    this.Invoke(new DelInvoke(delegate()
                    {
                        this.cboServer.SelectedIndex = 0;
                    }));


                    AddMessage("正在加载副本配置...");
                    #region 加载副本配置文件
                    DataSet ds = new DataSet();
                    ds.ReadXml("config/fb.config");
                    DataTable dt = ds.Tables[0];
                    this.Invoke(new DelInvoke(delegate()
                    {
                        this.cboFB.DataSource = dt;
                        this.cboFB.ValueMember = "envirid";
                        this.cboFB.DisplayMember = "fbname";
                    }));
                    #endregion
                    AddMessage("正在加载野外场景配置...");
                    #region 加载野外场景文件
                    DataSet dsEnvir = new DataSet();
                    dsEnvir.ReadXml("config/envir.config");

                    envidt = dsEnvir.Tables[0];

                    this.Invoke(new DelInvoke(delegate()
                    {
                        this.cboEnvir1.DataSource = envidt.Copy();
                        this.cboEnvir1.DisplayMember = "name";
                        this.cboEnvir1.ValueMember = "id";

                        this.cboEnvir2.DataSource = envidt.Copy();
                        this.cboEnvir2.DisplayMember = "name";
                        this.cboEnvir2.ValueMember = "id";

                        this.cboEnvir3.DataSource = envidt.Copy();
                        this.cboEnvir3.DisplayMember = "name";
                        this.cboEnvir3.ValueMember = "id";

                        this.cboEnvir4.DataSource = envidt.Copy();
                        this.cboEnvir4.DisplayMember = "name";
                        this.cboEnvir4.ValueMember = "id";

                        this.cboEnvir5.DataSource = envidt.Copy();
                        this.cboEnvir5.DisplayMember = "name";
                        this.cboEnvir5.ValueMember = "id";

                        this.cboEnvir6.DataSource = envidt.Copy();
                        this.cboEnvir6.DisplayMember = "name";
                        this.cboEnvir6.ValueMember = "id";
                    }));
                    #endregion
                    AddMessage("正在加载全局配置...");
                    #region 加载配置文件
                    this.Invoke(new DelInvoke(delegate()
                    {
                        #region 读取上次登录信息
                        this.txtName.Text = ini.ReadString("user", "email", "");
                        this.txtPwd.Text = ini.ReadString("user", "pwd", "");
                        this.cboServer.SelectedValue = ini.ReadString("user", "server", "10001");
                        int sid = ini.ReadInteger("user", "server", 10001);
                        string sname = ini.ReadString("user", "sname", "玉门关一服");
                        this.cboServer.SelectedItem = new CboItem(sid, sname);
                        //this.cboServer.SelectedItem = new System.Web.UI.WebControls.ListItem(sname, sid.ToString());

                        #endregion

                        #region 读取上次跑商交易路线

                        this.cboline1.SelectedItem = new CboItem(ini.ReadInteger("line1", "id", 0), ini.ReadString("line1", "name", ""));
                        this.cboline2.SelectedItem = new CboItem(ini.ReadInteger("line2", "id", 0), ini.ReadString("line2", "name", ""));
                        this.cboline3.SelectedItem = new CboItem(ini.ReadInteger("line3", "id", 0), ini.ReadString("line3", "name", ""));

                        this.cboHuowu11.Text = ini.ReadString("line1", "huowu1", "");
                        this.cboHuowu12.Text = ini.ReadString("line1", "huowu2", "");
                        this.cboHuowu21.Text = ini.ReadString("line2", "huowu1", "");
                        this.cboHuowu22.Text = ini.ReadString("line2", "huowu2", "");
                        this.cboHuowu31.Text = ini.ReadString("line3", "huowu1", "");
                        this.cboHuowu32.Text = ini.ReadString("line3", "huowu2", "");
                        #endregion

                        #region 读取上次打野怪配置文件

                        this.cboEnvir1.SelectedValue = ini.ReadInteger("envir", "envir1", 28);
                        this.cboGuai1.SelectedItem = null;
                        this.cboGuai1.Text = ini.ReadString("envir", "guaiwu1", "");
                        this.cboEnvir2.SelectedValue = ini.ReadInteger("envir", "envir2", 28);
                        this.cboGuai2.SelectedItem = null;
                        this.cboGuai2.Text = ini.ReadString("envir", "guaiwu2", "");
                        this.cboEnvir3.SelectedValue = ini.ReadInteger("envir", "envir3", 28);
                        this.cboGuai3.SelectedItem = null;
                        this.cboGuai3.Text = ini.ReadString("envir", "guaiwu3", "");
                        this.cboEnvir4.SelectedValue = ini.ReadInteger("envir", "envir4", 28);
                        this.cboGuai4.SelectedItem = null;
                        this.cboGuai4.Text = ini.ReadString("envir", "guaiwu4", "");
                        this.cboEnvir5.SelectedValue = ini.ReadInteger("envir", "envir5", 28);
                        this.cboGuai5.SelectedItem = null;
                        this.cboGuai5.Text = ini.ReadString("envir", "guaiwu5", "");

                        #endregion

                        #region 读取上次副本配置文件

                        this.cboFB.SelectedValue = ini.ReadInteger("FB", "id", 28);
                        this.numFBMax.Value = ini.ReadInteger("FB", "count", 1);
                        this.chkAutoGreen.Checked = ini.ReadBool("FB", "autosellGreen", false);
                        this.chkAutoWrite.Checked = ini.ReadBool("FB", "autosellWrite", true);
                        this.chkAutoGray.Checked = ini.ReadBool("FB", "autosellGray", true);
                        this.chkAutoBlue.Checked = ini.ReadBool("FB", "autosellBlue", false);
                        this.chkFBJJdz.Checked = ini.ReadBool("FB", "jjdouzi", true);
                        this.chkFBJJyao.Checked = ini.ReadBool("FB", "jjyao", true);
                        this.chkFBme.Checked = ini.ReadBool("FB", "saveme", true);
                        this.chkFBUsedz.Checked = ini.ReadBool("FB", "usedz", false);

                        #endregion

                        #region 读取上次技能配置文件
                        this.txtSearchFor.Text = ini.ReadString("jineng", "SearchForName", "");
                        this.cboEnvir6.SelectedValue = ini.ReadInteger("jineng", "SearchForID", 28);
                        #endregion
                    }));
                    #endregion
                    AddMessage("所有配置加载完成...");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("启动程序出现异常：" + ex.Message + "请尽快联系作者，完善。");
                }
            }));
            tGAstart.Start();

        }

        private void frmMain_LocationChanged(object sender, EventArgs e)
        {
            //如果使窗体最小化
            if (WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = false;
            }
            else
            {
                this.ShowInTaskbar = true;
            }

            this.txtLog.SelectionStart = this.txtLog.Text.Length;
            this.txtLog.ScrollToCaret();
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dr = MessageBox.Show("确定要退出《黄金时代》吗？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                e.Cancel = false;
            }
            else
            {
                e.Cancel = true;
                return;
            }
            if (!string.IsNullOrEmpty(this.txtLog.Text))
            {
                Config.SaveConfig(this.txtLog.Text);
            }

            this.notifyIcon1.Visible = false;

            Application.ExitThread();
            Application.Exit();

        }

        #endregion

        private void timer1_Tick(object sender, EventArgs e)
        {
            int num = 0;

            int.TryParse(this.txtTime.Tag + "", out num);
            if (starttime > 10 * 60)
            {
                starttime = 0;
                GA.GetJJStatus();
            }

            if (num > 0)
            {
                num--;
                this.SetTimes(num);
                starttime++;
                //this.textBox2.Text = num.ToString();
                numtime = num;
            }
            else if (num == 0)
            {
                this.txtTime.Text = "操作进行中...";
                this.txtTime.Tag = "-999";
                if (tGAPS != null && tGAPS.ThreadState == (ThreadState.Suspended | ThreadState.Background))
                {
                    tGAPS.Resume();
                    this.SetTimerState(false);
                }
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            string name = this.txtName.Text;
            string pwd = this.txtPwd.Text;
            //System.Web.UI.WebControls.ListItem server = this.cboServer.SelectedItem as System.Web.UI.WebControls.ListItem;
            CboItem server = this.cboServer.SelectedItem as CboItem;

            string sid = "";
            if (server != null)
            {
                sid = server.Key.ToString();

                for (int i = 0; i < sids.Split(',').Length; i++)
                {
                    if (sid == sids.Split(',')[i])
                    {
                        Setting.SetString("sid", sid);
                        Setting.SetString("surl", surls.Split(',')[i]);

                        break;
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择需要登录的服务器。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            string msg = "";

            if (name == "" || pwd == "")
            {
                MessageBox.Show("用户名或密码不能为空！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else if (name.IndexOf("@") == -1)
            {
                MessageBox.Show("电子邮件格式不正确！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else if (pwd.Length < 6)
            {
                MessageBox.Show("密码的长度必须大于6位！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            this.btnLogin.Enabled = false;
            this.txtName.Enabled = false;
            this.txtPwd.Enabled = false;
            this.cboServer.Enabled = false;
            tGALogin = new Thread(new ThreadStart(delegate()
            {

                try
                {
                    bool b = GAClient.LoadConfig(name + ".cookie");
                    if (b)
                    {
                        this.AddMessage("密码已经保存，自动登录。");
                    }
                    else
                    {
                        GA.Login(name, pwd, out msg);
                    }
                    if (!string.IsNullOrEmpty(msg))
                    {
                        this.AddMessage(msg);
                        MessageBox.Show(msg, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.btnLogin.Invoke(new DelInvoke(delegate()
                        {
                            this.btnLogin.Enabled = true;
                            this.txtName.Enabled = true;
                            this.txtPwd.Enabled = true;
                            this.cboServer.Enabled = true;
                        }));

                        return;
                    }
                    this.AddMessage("帐号" + name + "登录成功...");

                    this.Invoke(new DelInvoke(delegate()
                    {
                        ini.WriteString("user", "email", this.txtName.Text);
                        ini.WriteString("user", "pwd", this.txtPwd.Text);
                        ini.WriteString("user", "server", sid);
                        ini.WriteString("user", "sname", this.cboServer.Text);
                    }));
                    bool isopen = GA.GetInfo();
                    GAClient.SaveConfig(name + ".cookie");
                    if (!isopen)
                    {
                        this.Invoke(new DelInvoke(delegate()
                        {
                            this.txtName.Enabled = true;
                            this.txtPwd.Enabled = true;
                            this.btnLogin.Enabled = true;
                            this.btnExit.Enabled = true;
                            this.cboServer.Enabled = true;
                        }));
                    }
                    this.Invoke(new DelInvoke(delegate()
                    {
                        string notifyText = "黄金时代辅助qq:76459399\n帐号：" + name;
                        notifyText += "\n服务器：" + this.cboServer.Text;
                        notifyText += "\n昵称：" + UserInfo.Name;
                        this.notifyIcon1.Text = notifyText;
                        //this.notifyIcon1.Text += "\n所在服务器：" + this.cboServer.Text;
                        //this.notifyIcon1.Text += "\n昵称：" + UserInfo.Name;

                        this.Text = defaulttitle + " -- " + this.cboServer.Text + " -- " + UserInfo.Name + "(" + name + ")";
                    }));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }));
            tGALogin.IsBackground = true;
            tGALogin.Start();
            this.AddMessage("正在验证帐号密码...");
            //this.Login(name, pwd, out msg);

        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (tGALogin == null || string.IsNullOrEmpty(UserInfo.Name))
            {
                MessageBox.Show("对不起，您还没有登录，请登录后再跑商。");
                return;
            }
            if (UserInfo.JJNames.Length == 0)
            {
                this.AddMessage("对不起，您没有家将不能使用家将跑商功能。");
                return;
            }
            Setting.SetBool("PSroad", this.radPSroad.Checked);
            Setting.SetBool("PStransport", this.chkRepair.Checked);
            CboItem line1 = null, line2 = null, line3 = null;
            this.Invoke(new DelInvoke(delegate() { line1 = this.cboline1.SelectedItem as CboItem; line2 = this.cboline2.SelectedItem as CboItem; line3 = this.cboline3.SelectedItem as CboItem; }));


            if (line1 == null) { MessageBox.Show("没有选择线路1!"); return; }
            if (line2 == null) { MessageBox.Show("没有选择线路2!"); return; }

            int cid1 = 0, cid2 = 0, cid3 = 0;
            cboline1.Invoke(new GoldenAgeHelper.frmMain.DelInvoke(delegate() { cid1 = Convert.ToInt32((cboline1.SelectedItem as CboItem).Key); }));
            cboline2.Invoke(new GoldenAgeHelper.frmMain.DelInvoke(delegate() { cid2 = Convert.ToInt32((cboline2.SelectedItem as CboItem).Key); }));
            cboline3.Invoke(new GoldenAgeHelper.frmMain.DelInvoke(delegate() { try { cid3 = Convert.ToInt32((cboline3.SelectedItem as CboItem).Key); } catch { } }));

            string bname1 = "", bname2 = "", bname3 = "", bname11 = "", bname21 = "", bname31 = "";
            Invoke(new GoldenAgeHelper.frmMain.DelInvoke(delegate()
            {
                bname1 = cboHuowu11.Text;
                bname11 = cboHuowu12.Text;
                bname2 = cboHuowu21.Text;
                bname21 = cboHuowu21.Text;
                bname3 = cboHuowu31.Text;
                bname31 = cboHuowu31.Text;
            }));

            if (this.cboline1.SelectedItem != null)
            {
                ini.WriteInteger("line1", "id", cid1);
                ini.WriteString("line1", "name", line1.Value);
                ini.WriteString("line1", "huowu1", bname1);
                ini.WriteString("line1", "huowu2", bname11);
            }
            else
            {
                ini.WriteString("line1", "id", "");
                ini.WriteString("line1", "name", "");
                ini.WriteString("line1", "huowu1", "");
                ini.WriteString("line1", "huowu2", "");
            }
            if (this.cboline2.SelectedItem != null)
            {
                ini.WriteInteger("line2", "id", cid2);
                ini.WriteString("line2", "name", line2.Value);
                ini.WriteString("line2", "huowu1", bname2);
                ini.WriteString("line2", "huowu2", bname21);
            }
            else
            {
                ini.WriteString("line2", "id", "");
                ini.WriteString("line2", "name", "");
                ini.WriteString("line2", "huowu1", "");
                ini.WriteString("line2", "huowu2", "");
            }
            if (this.cboline3.SelectedItem != null)
            {
                ini.WriteInteger("line3", "id", cid3);
                ini.WriteString("line3", "name", line3.Value);
                ini.WriteString("line3", "huowu1", bname3);
                ini.WriteString("line3", "huowu2", bname31);
            }
            else
            {
                ini.WriteString("line3", "id", "");
                ini.WriteString("line3", "name", "");
                ini.WriteString("line3", "huowu1", "");
                ini.WriteString("line3", "huowu2", "");
            }


            if (tGAPS == null || tGAPS.ThreadState != ThreadState.Running && tGAPS.ThreadState != ThreadState.Background)
            {
                tGAPS = new Thread(new ThreadStart(delegate()
                {
                    while (true)
                    {

                        //bool b = Monitor.TryEnter(GA.lockvar);
                        //if (!b)
                        //{
                        //    AddMessage("当前正在进行其他操作，操作完成会立刻执行。请等待.....");
                        //}
                        //Monitor.Enter(GA.lockvar);

                        int toid = GA.GetJJStatus();

                        GA.GoCity(toid);
                        if (Setting.GetBool("PStransport"))
                        {
                            GA.RepairTransport(0);
                        }

                        //是否不考虑价格卖出
                        bool bsell = this.chkSell.Checked;
                        //卖出
                        GA.SellHuowu(bsell);

                        int gocid = 0;
                        string buyname = "";
                        //if (UserInfo.JJ == cid1)
                        //{
                        //    gocid = cid2;
                        //    buyname = bname1;
                        //}
                        if (toid == cid1)
                        {
                            gocid = cid2;
                            buyname = bname1;
                        }
                        else if (cid3 != 0 && toid == cid2)
                        {
                            gocid = cid3;
                            buyname = bname2;
                        }
                        else if (cid3 != 0 && toid == cid3)
                        {
                            gocid = cid1;
                            buyname = bname3;
                        }
                        else
                        {
                            gocid = cid1;
                            buyname = bname2;
                        }
                        //买入
                        GA.BuyHuowu(toid, gocid, buyname);

                        int time = GA.MoveTo(gocid, User.JJ);

                        Thread.Sleep(2000);
                    }

                    this.btnStart.Enabled = true;
                }));
                tGAPS.IsBackground = true;
                tGAPS.Start();
                this.btnStart.Enabled = false;
            }
            else
            {
                this.btnStart.Enabled = true;
            }
        }

        #region 窗体方法，委托方法

        private void SetInfo(string info)
        {
            try
            {
                this.Invoke(new DelInvoke(delegate()
                {
                    this.txtInfo.Text = info;
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void AddMessage(string msg)
        {
            try
            {
                this.Invoke(new DelInvoke(delegate()
                {
                    this.txtLog.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + msg + "\r\n");
                    this.txtLog.SelectionStart = this.txtLog.Text.Length - 1;
                    this.txtLog.ScrollToCaret();
                }));
            }
            catch (Exception ex)
            {

            }
        }

        private void SetTimes(int num)
        {
            this.txtTime.Invoke(new DelInvoke(delegate()
            {
                this.txtTime.Text = Util.GetTime(num);
                this.txtTime.Tag = num;
            }));
        }

        private void SetTimerState(bool status)
        {
            //bool b = Monitor.TryEnter(GA.lockvar);
            //Monitor.Exit(GA.lockvar);

            this.Invoke(new DelInvoke(delegate()
            {
                if (status)
                {
                    this.timerPS.Start();
                    if (tGAPS != null)
                    {
                        tGAPS.Suspend();
                    }
                }
                else
                {
                    this.timerPS.Stop();
                }
            }));
        }

        private void SetAutoStartTimer3(int num)
        {
            SetTimes3(num);
            SetTimerState3(true);
        }

        private void SetTimes3(int num)
        {
            this.txtAllTime.Invoke(new DelInvoke(delegate()
            {
                this.txtAllTime.Text = Util.GetTime(num);
                this.txtAllTime.Tag = num;
            }));
        }

        private void SetTimerState3(bool status)
        {
            this.Invoke(new DelInvoke(delegate()
            {
                if (status)
                {
                    this.timerMap.Start();
                    if (tGAAuto != null)
                    {
                        tGAAuto.Suspend();
                    }
                }
                else
                {
                    this.timerMap.Stop();
                }
            }));
        }

        #endregion

        private void button2_Click(object sender, EventArgs e)
        {
            /*购买测试*/
            //转到家将所在位置
            //GAClient.DownloadString("http://t1.nexttime.cn/cityview?cid=" + UserInfo.JJ.ToString() + "&ts=" + Util.GetTime());
            //GAClient.DownloadString("http://t1.nexttime.cn/cityview?cid=" + UserInfo.Me.ToString() + "&ts=" + Util.GetTime());
            //this.AddMessage("已进入家将所在地【" + City.GetCity(UserInfo.JJ) + "】。");
            //BuyHuowu();

            /*获取全部商品信息资料*/
            //test = new Thread(new ThreadStart(delegate()
            //{
            //    //basic.BaseFile bf = new GoldenAgeHelper.basic.BaseFile();
            //    //bf.Eve += new showMSG(AddMessage);
            //    //bf.HuowuBase();

            //    //int envirid = 29;
            //    //AttaNpc(24, "道长");
            //    //AttaNpc(29, "密探");
            //    //AttaNpc(25, "野猪");

            //}));
            //test.Start();

            //http://t1.nexttime.cn/map?t=6&ts=1274802509281
            //string tt = "V.showMap({fw:[13,1,23]});";
            //string gone = GARegex.GetString(tt, "{fw:[", "]}");
            //string[] arrgo = gone.Split(',');
            //int cid = City.GetCityID("蒲州");
            //List<object> list = City.GetCityPoint(cid);
            //DataTable dtt = City.GetCityPoint(Convert.ToInt32(list[0]), Convert.ToInt32(list[1]), arrgo);
            //MessageBox.Show(City.GetCity(cid) + "最近的距离是：" + dtt.Rows[0]["cid"] + dtt.Rows[0]["cname"]);

            //DataTable dtt2 = City.Move(new Point(0, 0), new Point(0, 50));

            //http://t1.nexttime.cn/faeve?action=lookfor&ts=1273976581906
            //tocity=娲涢槼&tocityId=23&followerId=52347&

            //test = new Thread(new ThreadStart(delegate()
            //{
            //    //GA.LookForJJ();
            //    //GA.LookForMe(PayType.XianDou);
            //    GA.JJCmd(0, PayType.None, JJCMD.collect, "1");
            //}));
            //test.Start();

            test = new Thread(new ThreadStart(delegate()
            {

                //GA.GoHome();
                GA.SellZB(ZBType.装备, ZBRare.灰色);
                GA.SellZB(ZBType.装备, ZBRare.白色);
                //GA.SellZB(ZBType.装备, ZBRare.绿色);
            }));
            test.IsBackground = true;
            test.Start();


        }

        private void button3_Click(object sender, EventArgs e)
        {
            test = new Thread(new ThreadStart(delegate()
            {
                //string t = GAClient.DownloadString(GA.RootURL + "/sys/js/socket.swf?v=1214001");
                //GA.GoCity(UserInfo.JJ);
                //GA.SellHuowu(true);

                //Caiji();

                //GAPosition.environ();
                //GAPosition.Envir(Envir.风景区);

                //Wuguan();

                //GAPosition.environ();
                //GAPosition.Envir(Envir.风景区);
                //GAPosition.Envir(Envir.村落);
                //GAPosition.Envir(Envir.高山);
                //GAPosition.Envir(Envir.河流);
                //GAPosition.Envir(Envir.农田);
                //GAPosition.Envir(Envir.遗迹);
                //GAPosition.Envir(Envir.树林);




                //MessageBox.Show(txt);



                //GA.RepairTransport(0);
            }));
            test.Start();


            //List<object> list1 = City.GetCityPoint(1);
            //List<object> list2 = City.GetCityPoint(23);

            //List<object> list = City.GetCityPoint(City.GetCityID("蒲州"));

            //DataTable dt33 = City.Move(new Point(Convert.ToInt32(list[0]), Convert.ToInt32(list[1])), new Point(Convert.ToInt32(list1[0]), Convert.ToInt32(list1[1])));

            //DataTable dt331 = City.Move(new Point(Convert.ToInt32(list[0]), Convert.ToInt32(list[1])), new Point(Convert.ToInt32(list2[0]), Convert.ToInt32(list2[1])));
        }

        private void Wuguan()
        {
            GAPosition.Building(31);
            GA.Sleep();
            string text = GAPosition.Building(31, "sp");
            GA.Sleep(1000);
            GroupCollection coll = GARegex.GetString(text, "您今天已经发起了 <strong class='s2'>(?<num>[0-9]+)</strong> / (?<all>[0-9]+) 次挑战了。");
            string numstr = coll["num"].Value;
            string allstr = coll["all"].Value;
            int num = Convert.ToInt32(numstr);
            int all = Convert.ToInt32(allstr);
            AddMessage("今天已经发起了[" + numstr + "/" + allstr + "]场比武了。");
            string time = GARegex.GetString(text, "<span s='", "' stat='start' tid='jingjichang'");
            if (!string.IsNullOrEmpty(time))
            {
                AddMessage("无法战斗！剩余时间：" + Util.GetTime(Convert.ToInt32(time)));
                Thread.Sleep(Convert.ToInt32(time) * 1000 + 1000);
            }
            //<a href='#' class='s13' u='/duv?userId=2420'>地师</a></td><td>98</td><td>22</td><td><a href='#' u='/uspf?oid=2420' class='s13'>挑战</a>
            MatchCollection coll2 = GARegex.Matches(text, "<a href='#' class='s13' u='/duv\\?userId=(?<id>[0-9]+)'>(?<name>[\\s\\S]+?)</a></td><td>(?<pm>[0-9]+)</td><td>(?<lvl>[0-9]+)</td>");
            if (coll2.Count != 0)
            {
                for (int i = coll2.Count - 1; i >= 0; i--)
                {
                    string id = coll2[i].Groups["id"].Value;
                    string name = coll2[i].Groups["name"].Value;
                    string lvl = coll2[i].Groups["lvl"].Value;
                    AddMessage("自动选择攻击[" + name + "]等级[" + lvl + "]。");
                    string result = GAClient.DownloadString(GA.ROOT_URL + "/uspf?oid=" + id + "&ts=" + Util.GetTime());
                    string alert = GA.GetAlert(result);
                    alert = GARegex.DelHtml(alert);
                    AddMessage(alert);
                    break;
                }
            }
            //
        }

        private void btnFB_Click(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(this.cboFB.SelectedValue);
            int count = (int)this.numFBMax.Value;

            bool b1 = this.chkAutoGreen.Checked;
            bool b2 = this.chkAutoWrite.Checked;
            bool b3 = this.chkFBJJdz.Checked;
            bool b4 = this.chkFBJJyao.Checked;
            bool b5 = this.chkFBme.Checked;
            bool b6 = this.chkFBUsedz.Checked;
            bool b7 = this.chkAutoBlue.Checked;
            bool b8 = this.chkAutoGray.Checked;

            ini.WriteInteger("FB", "id", id);
            ini.WriteInteger("FB", "count", count);
            ini.WriteBool("FB", "autosellWrite", b2);
            ini.WriteBool("FB", "jjdouzi", b3);
            ini.WriteBool("FB", "jjyao", b4);
            ini.WriteBool("FB", "saveme", b5);
            ini.WriteBool("FB", "usedz", b6);
            ini.WriteBool("FB", "autosellGreen", b1);
            ini.WriteBool("FB", "autosellGray", b8);
            ini.WriteBool("FB", "autosellBlue", b7);

            Setting.SetBool("saveme", b5);
            Setting.SetBool("usedz", b6);
            Setting.SetBool("jjyao", b4);
            Setting.SetBool("jjdouzi", b3);

            tGAFB = new Thread(new ThreadStart(delegate()
            {
                //bool block = Monitor.TryEnter(GA.lockvar);
                //if (!block)
                //{
                //    AddMessage("当前正在进行其他操作，操作完成将立即打副本，请等待......");
                //}
                //Monitor.Enter(GA.lockvar);
                for (int i = 0; i < count; i++)
                {
                    GA.FB(id);

                    List<ZBRare> list = new List<ZBRare>();
                    if (b8) list.Add(ZBRare.灰色);
                    if (b2) list.Add(ZBRare.白色);
                    if (b1) list.Add(ZBRare.绿色);
                    if (b7) list.Add(ZBRare.蓝色);
                    if (list.Count > 0) GA.SellZB(ZBType.装备, list);

                    AddMessage("第" + (i + 1) + "次打副本完成。");
                }
                this.Invoke(new DelInvoke(delegate() { this.btnFB.Enabled = true; }));
                //Monitor.Exit(GA.lockvar);
            }));
            tGAFB.IsBackground = true;
            tGAFB.Start();
            this.btnFB.Enabled = false;


        }

        private void cboline1_Leave(object sender, EventArgs e)
        {
            ComboBox box = sender as ComboBox;
            if (box != null)
            {
                int cid = City.GetCityID(box.Text);
                if (cid != 0)
                {
                    if (box.SelectedItem == null)
                    {
                        box.SelectedItem = new CboItem(cid, box.Text);
                    }
                }
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.WindowState = FormWindowState.Normal;
            }
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {

            if (e.Button == MouseButtons.Left)
            {
                this.WindowState = FormWindowState.Normal;
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            try { tGAPS.Abort(); }
            catch { }
            try { tGAAuto.Abort(); }
            catch { }
            try { tGAFB.Abort(); }
            catch { }
            try { tGAJJ.Abort(); }
            catch { }
            try { tGALogin.Abort(); }
            catch { }
            try { tGAPS.Abort(); }
            catch { }
            try { tGAstart.Abort(); }
            catch { }

            this.btnLogin.Enabled = true;
            this.btnExit.Enabled = true;
            this.txtName.Enabled = true;
            this.txtPwd.Enabled = true;
            this.cboServer.Enabled = true;


        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string where = "1=1";
            if (this.cboFindCity.SelectedItem != null)
            {
                where = "a.cid='" + (this.cboFindCity.SelectedItem as CboItem).Key + "'";
            }
            else if (!string.IsNullOrEmpty(this.cboFindCity.Text))
            {
                where = "(a.cname in ('" + this.cboFindCity.Text.Replace(",", "','") + "') or c.huowuname in ('" + this.cboFindCity.Text.Replace(",", "','") + "'))";
            }
            DataSet ds = Database.helper.ExecuteQuery("select a.cid,a.cname,c.huowuname,b.price,b.num from city a,cityhuowu b,huowu c where a.cid=b.cid and b.hid=c.hid and " + where);
            this.dataGridView1.DataSource = ds.Tables[0];
        }

        private void btnEnd_Click(object sender, EventArgs e)
        {
            this.btnStart.Enabled = true;
            tGAPS = null;
            SetTimerState(false);
            if (tGAPS != null)
            {

                //tPS = null;
                //if (tPS!=null && tPS.ThreadState ==( ThreadState.Suspended | ThreadState.Background))
                //{
                //    tPS.Resume();
                //}
                //if (tPS!=null && tPS.ThreadState == ThreadState.Running)
                //{
                //    tPS.Abort();
                //}
            }

            //Monitor.TryEnter(GA.lockvar);
            //Monitor.Exit(GA.lockvar);
        }

        private void btnShowMap_Click(object sender, EventArgs e)
        {
            frmMap map = new frmMap();
            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                int id = Convert.ToInt32(row.Cells["colcid"].Value);
                if (id != 0 && Convert.ToInt32(row.Cells["colnum"].Value) > 0)
                {
                    map.AddCity(id);
                }
                else if (Convert.ToInt32(row.Cells["colnum"].Value) < 0)
                {
                    map.AddCityNone(id);
                }
            }
            map.Show();
        }

        private void btnAtta_Click(object sender, EventArgs e)
        {
            Setting.SetBool("YWrite", this.chkYWhite.Checked);
            Setting.SetBool("YGray", this.chkYGray.Checked);
            Setting.SetBool("YGreen", this.chkYGreen.Checked);

            this.btnAtta.Enabled = false;
            tGAAtta = new Thread(new ThreadStart(delegate()
            {
                //bool b = Monitor.TryEnter(GA.lockvar);
                //if (!b)
                //{
                //    AddMessage("正在等待其他操作，请稍后....");
                //}

                //Monitor.Enter(GA.lockvar);

                int time = ShowStatus(tGAAtta);
                if (time != 0)
                {
                    string sta = GA.GetUserStatus();
                    AddMessage(GARegex.DelHtml(sta) + ",剩余时间：" + Util.GetTime(time));
                    Thread.Sleep(time);
                }


                GA.GoCity(UserInfo.Me, User.Me);

                object value1 = null;
                object value2 = null;
                object value3 = null;
                object value4 = null;
                object value5 = null;

                string text1 = null;
                string text2 = null;
                string text3 = null;
                string text4 = null;
                string text5 = null;
                this.Invoke(new DelInvoke(delegate()
                {
                    value1 = this.cboEnvir1.SelectedValue;
                    value2 = this.cboEnvir2.SelectedValue;
                    value3 = this.cboEnvir3.SelectedValue;
                    value4 = this.cboEnvir4.SelectedValue;
                    value5 = this.cboEnvir5.SelectedValue;

                    text1 = this.cboGuai1.Text;
                    text2 = this.cboGuai2.Text;
                    text3 = this.cboGuai3.Text;
                    text4 = this.cboGuai4.Text;
                    text5 = this.cboGuai5.Text;

                    ini.WriteString("envir", "envir1", value1 + "");
                    ini.WriteString("envir", "guaiwu1", text1);
                    ini.WriteString("envir", "envir2", value2 + "");
                    ini.WriteString("envir", "guaiwu2", text2);
                    ini.WriteString("envir", "envir3", value3 + "");
                    ini.WriteString("envir", "guaiwu3", text3);
                    ini.WriteString("envir", "envir4", value4 + "");
                    ini.WriteString("envir", "guaiwu4", text4);
                    ini.WriteString("envir", "envir5", value5 + "");
                    ini.WriteString("envir", "guaiwu5", text5);

                }));

                if (value1 != null && !string.IsNullOrEmpty(text1))
                    GA.AttaNpc(Convert.ToInt32(value1), text1, 0);
                if (value2 != null && !string.IsNullOrEmpty(text2))
                    GA.AttaNpc(Convert.ToInt32(value2), text2, 0);
                if (value3 != null && !string.IsNullOrEmpty(text3))
                    GA.AttaNpc(Convert.ToInt32(value3), text3, 0);
                if (value4 != null && !string.IsNullOrEmpty(text4))
                    GA.AttaNpc(Convert.ToInt32(value4), text4, 0);
                if (value5 != null && !string.IsNullOrEmpty(text5))
                    GA.AttaNpc(Convert.ToInt32(value5), text5, 0);

                this.AddMessage("攻击野外结束。");
                //AttaNpc(24, "道长");
                //AttaNpc(29, "密探");
                //AttaNpc(25, "野猪");
                try
                {
                    this.Invoke(new DelInvoke(delegate() { this.btnAtta.Enabled = true; }));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }


                List<ZBRare> list = new List<ZBRare>();
                if (Setting.GetBool("YGray"))
                {
                    list.Add(ZBRare.灰色);
                }
                if (Setting.GetBool("YWrite"))
                {
                    list.Add(ZBRare.白色);
                }
                if (Setting.GetBool("YGreen"))
                {
                    list.Add(ZBRare.绿色);
                }
                if (list.Count > 0)
                {
                    GA.SellZB(ZBType.装备, list);
                }
                if (true)/*自动修理装备*/
                {
                    GA.RepairZB();
                }

                //Monitor.Enter(GA.lockvar);
                //Monitor.Exit(GA.lockvar);
            }));
            tGAAtta.IsBackground = true;
            tGAAtta.Start();
        }

        private void cboEnvir1_Leave(object sender, EventArgs e)
        {
            ComboBox box = sender as ComboBox;
            if (box != null)
            {
                if (box.SelectedItem == null)
                {
                    foreach (DataRow row in envidt.Rows)
                    {
                        if (row["name"].Equals(box.Text))
                        {
                            box.SelectedValue = row["id"];
                            break;
                        }
                    }
                }
            }
        }

        private void cboEnvir1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox box = sender as ComboBox;

            int i = 0;
            i = Convert.ToInt32(box.Name.Substring(box.Name.Length - 1));

            Control[] con = this.Controls.Find("cboGuai" + i, true);

            if (con[0] != null)
            {
                foreach (DataRow row in envidt.Rows)
                {
                    if (row["id"].Equals(box.SelectedValue))
                    {
                        (con[0] as ComboBox).Items.Clear();
                        (con[0] as ComboBox).Items.Add(row["npc1"]);
                        (con[0] as ComboBox).Items.Add(row["npc2"]);
                        (con[0] as ComboBox).Items.Add(row["npc3"]);
                        (con[0] as ComboBox).Text = row["npc1"].ToString();
                    }
                }
            }

        }

        private void 更新城市资料ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tGAFB = new Thread(new ThreadStart(delegate()
            {
                GA.GoCity(UserInfo.Me, User.Me);
                GA.BuyHuowu(UserInfo.Me);
            }));
            tGAFB.Start();

        }

        private void btnLookFor_Click(object sender, EventArgs e)
        {
            int count = (int)this.numLookFor.Value;
            tGAJJ = new Thread(new ThreadStart(delegate()
            {
                AddMessage("自己开始准备寻访，次数为：" + count);
                for (int i = 0; i < count; i++)
                {
                    GA.LookForMe();
                    AddMessage("自己第[" + (i + 1) + "]次寻访结束。");
                }
                this.btnLookFor.Enabled = true;
            }));
            tGAJJ.IsBackground = true;
            tGAJJ.Start();
            this.btnLookFor.Enabled = false;
        }

        private void btnLookFor1_Click(object sender, EventArgs e)
        {
            int cid = 0;
            //int.TryParse(this.cboLookFor.SelectedItem + "", out cid);
            CboItem item = this.cboJJlookfor.SelectedItem as CboItem;
            if (item != null)
            {
                cid = item.Key;
            }
            if (string.IsNullOrEmpty(UserInfo.Name))
            {
                AddMessage("请登录后进行操作。");
                return;
            }

            int count = (int)this.numJJlookfor.Value;
            int num = (int)this.numlookforMax.Value;

            tGAJJ = new Thread(new ThreadStart(delegate()
            {
                AddMessage("家将前往[" + City.GetCity(cid) + "]寻访(" + count + "次)正在准备中...");
                for (int i = 0; i < count; i++)
                {
                    //GA.LookForJJ(cid, PayType.None);
                    bool b = GA.JJLookFor(cid, num, PayType.None);
                    if (!b)
                    {
                        AddMessage("无法寻访，寻访结束。");
                        break;
                    }
                    AddMessage("家将在[" + City.GetCity(cid) + "]第" + (i + 1) + "次寻访完成。");
                }
                this.Invoke(new DelInvoke(delegate() { this.btnJJlookfor.Enabled = true; }));
            }));
            tGAJJ.IsBackground = true;
            tGAJJ.Start();
            this.btnJJlookfor.Enabled = false;

        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            int cid = 0;
            int.TryParse(this.cboLookFor.SelectedValue + "", out cid);
            if (string.IsNullOrEmpty(UserInfo.Name))
            {
                AddMessage("请登录后进行操作。");
                return;
            }
            string collecttime = this.cboCollectTime.Text;
            tGAJJ = new Thread(new ThreadStart(delegate()
            {
                GA.JJCollect(PayType.None, collecttime);
            }));
            tGAJJ.Start();
        }

        private void btnXiulian_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(UserInfo.Name))
            {
                AddMessage("请登录后进行操作。");
                return;
            }
            string collecttime = this.cboCollectTime.Text;
            tGAJJ = new Thread(new ThreadStart(delegate()
            {
                GA.JJXx();
            }));
            tGAJJ.Start();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            begintime++;
            int time = 0;
            int.TryParse(this.tstTime.Text, out time);
            if (!string.IsNullOrEmpty(UserInfo.Name))
            {
                if (begintime % (15 * 60) == 0)
                {
                    GA.GetUserStatus();
                }
                if ((begintime / 2) % 3600 == 0)
                {
                    //AddMessage("程序已经运行" + begintime / 3600 + "个小时，自动清理消息记录。");
                    Config.SaveConfig(this.txtLog.Text);
                    this.txtLog.Clear();
                    AddMessage("程序已经运行" + begintime / 3600 + "个小时，自动清理消息记录。");
                }
                int last = (int)(DateTime.Now - lastGrarden).TotalMilliseconds;

                if (lastGrarden == new DateTime() || last >= 60 * 60 * 1000)
                {
                    GA.Garden();
                    lastGrarden = DateTime.Now;
                }
            }

            this.tsslTotal.Text = "程序已运行" + Util.GetTime(begintime) + "，为您赚取了" + Util.GetFormatMoney(Setting.GetInt("money")) + "。";
        }

        private void btnBengin_Click(object sender, EventArgs e)
        {
            Setting.SetBool("isYe1", this.chkYe1.Checked);
            Setting.SetBool("isYe2", this.chkYe2.Checked);
            Setting.SetBool("isJLy", this.chkJLy.Checked);
            Setting.SetBool("isJXz", this.chkJXz.Checked);
            Setting.SetBool("isJXf", this.chkJXf.Checked);
            Setting.SetBool("isTili", this.chkTl.Checked);
            Setting.SetBool("isSWrite", this.chkSWrite.Checked);
            Setting.SetBool("isSGray", this.chkSGray.Checked);
            Setting.SetBool("isSGreen", this.chkSGreen.Checked);
            Setting.SetBool("isSBlue", this.chkSBlue.Checked);
            // MessageBox.Show(Setting.GetBool("isYe2").ToString());

            tGAAuto = new Thread(new ThreadStart(delegate()
            {
                //try
                //{
                if (!timerPS.Enabled)
                {
                    if (numtime > 0)
                    {
                        //AddMessage("正在进行其他操作，剩余时间：" + Util.GetTime(numtime));
                        //SetTimes3(numtime + 1000);
                        //SetTimerState3(true);
                    }
                    else if (numtime == 0)
                    {
                        AddMessage("...");
                    }
                    else
                    {
                        AddMessage("其他操作正在进行中,请先等待其他操作完成...");
                        this.Invoke(new DelInvoke(delegate()
                        {
                            this.btnLxStart.Enabled = true;
                            this.btnLxEnd.Enabled = false;
                        }));
                        return;
                    }
                }



                Auto();
                this.Invoke(new DelInvoke(delegate()
                {
                    this.btnLxStart.Enabled = true;
                    this.btnLxEnd.Enabled = false;
                }));
                //}
                //catch (Exception ex)
                //{
                //    AddMessage(ex.Message);
                //    MessageBox.Show("出错啦：" + ex.Message);
                //}
            }));
            tGAAuto.IsBackground = true;
            tGAAuto.Start();
            this.btnLxStart.Enabled = false;
            this.btnLxEnd.Enabled = true;
        }

        public void Lvyou()
        {
            //Monitor.Enter(GA.lockvar);
            GA.GoCity(UserInfo.Me);
            //http://t1.nexttime.cn/building9?ts=1274929437828
            GAPosition.Building(9);
            //http://t1.nexttime.cn/bkrq?ts=1274929507187
            GAClient.DownloadString(GA.ROOT_URL + "/bkrq?ts=" + Util.GetTime());//打听消息
            //http://t1.nexttime.cn/bkrq?skill=21&t=1&ts=1274929520109
            string result = GAClient.DownloadString(GA.ROOT_URL + "/bkrq?skill=21&t=1&ts=" + Util.GetTime());

            string where = GARegex.GetString(result, "<strong class=\"s2\">", "</strong>");
            if (result.IndexOf("您似乎还不会") != -1)
            {
                AddMessage("缺少旅游技能无法旅游。");
                return;
            }
            if (!string.IsNullOrEmpty(where))//如果提示存在
            {
                AddMessage("发现[ " + where + " ]可以旅游。");
                GAPosition.environ();
                int id = 0;
                switch (where)
                {
                    case "风景区":
                        id = 28;
                        break;
                    case "羊肠小道":
                        id = 21;
                        break;
                    case "村落":
                        id = 22;
                        break;
                    case "高山":
                        id = 26;
                        break;
                    case "河流":
                        id = 27;
                        break;
                    case "遗迹":
                        id = 24;
                        break;
                    default:
                        break;
                }
                string text2 = GAPosition.Envir(id);
                AddMessage("已经进入[" + where + "]。");
                MatchCollection coll = GARegex.Matches(text2, @"<div class='zb_i'><p class='s15'>需要技能：\[ (?<name>[\s\S]+?) \] <span>(?<value>[\s\S]+?)</span></p></div>");
                if (coll.Count > 0)
                {
                    for (int i = 0; i < coll.Count; i++)
                    {
                        if (coll[i].Success)
                        {
                            string name = coll[0].Groups["name"].Value;
                            string value = coll[0].Groups["value"].Value;
                            //http://t1.nexttime.cn/tf?ts=1274930885156
                            string texet2 = GAClient.DownloadString(GA.ROOT_URL + "/tf?ts=" + Util.GetTime());
                            //<p>您今天已旅游和寻找生物 <strong class="s3">0</strong> / <strong class="s2">15</strong> 次。</p>
                            //您今天已旅游和寻找生物 <strong class="s3">0</strong> / <strong class="s2">15</strong> 次
                            GroupCollection coll3 = GARegex.GetString(texet2, "<p>您今天已旅游和寻找生物 <strong.+?>(?<min>[0-9]+)</strong> / <strong.+?>(?<max>[0-9]+)</strong> 次。</p>");
                            string minstr = coll3["min"].Value;
                            string maxstr = coll3["max"].Value;
                            int min, max;
                            int.TryParse(minstr, out min);
                            int.TryParse(maxstr, out max);
                            AddMessage("您今天已旅游和寻找生物" + min + "/" + max + "。");

                            if (min == max)
                            {
                                AddMessage("已经达到最大次数,无法继续旅游！");
                                return;
                            }
                            else
                            {
                                NameValueCollection data = new NameValueCollection();
                                //mt=-1&mode=start&
                                data.Add("mt", "-1");
                                data.Add("mode", "start");
                                string result2 = GAClient.ClientUrl(GA.ROOT_URL + "/tf?ts=" + Util.GetTime(), data);
                                int time = GARegex.GetInt(result2, " s='", "'");
                                AddMessage("正在[" + where + "]旅游(技能点：" + value + ")，剩余时间" + Util.GetTime(time) + "...");
                                this.SetTimes3(time);

                                //Monitor.Exit(GA.lockvar);

                                this.SetTimerState3(true);
                                AddMessage("旅游结束！");
                            }
                        }
                    }

                    Lvyou();
                }
            }
        }

        public void Caiji()
        {
            GAPosition.environ();
            string text = GAPosition.Envir(23);

            GroupCollection coll = GARegex.GetString(text, "' u='/cf?i=(?<index>[0-9])&u=(?<u>[0-9]+?)' ");
            AddMessage("共有" + coll.Count + "处采集。");
            if (coll.Count > 0)
            {
                string index = coll["index"].Value;
                string u = coll["u"].Value;
                string tt = GAClient.DownloadString(GA.ROOT_URL + "/cf?i=" + index + "&u=" + u + "&ts=" + Util.GetTime());
                string time = GARegex.GetString(tt, " s='", "' ");
                AddMessage("正在采集，剩余时间" + Util.GetTime(Convert.ToInt32(time)));
                Thread.Sleep(Convert.ToInt32(time) * 1000);
                AddMessage("采集完成！");
            }
        }

        public void Auto()
        {
            while (true)
            {
                //Monitor.Enter(GA.lockvar);

                string state = GA.GetUserStatus();

                string all = "";
                all = GARegex.DelReturn(GARegex.DelHtml(state));
                int times = GARegex.GetInt(state, " s='", "'");
                if (times > 0)
                {
                    AddMessage(GARegex.DelReturn(GARegex.DelHtml(state)) + "！剩余时间：" + Util.GetTime(times));
                    this.SetTimes3(times);
                    //Monitor.Exit(GA.lockvar);
                    this.SetTimerState3(true);
                }
                else
                {
                    //Monitor.Exit(GA.lockvar);
                }



                if (Setting.GetBool("isJLy"))//是否旅游
                {
                    Lvyou();
                }
                /*寻找生物*/
                if (Setting.GetBool("isJXz"))
                {

                }

                GA.GoCity(UserInfo.Me);
                #region 打野怪

                if (UserInfo.Tili > 0 || (Setting.GetBool("isTili") && UserInfo.Tili <= 0))
                {
                    /*打野怪*/
                    if (Setting.GetBool("isYe1"))
                    {
                        GA.AttaNpc((int)Envir.风景区, "0", 0);
                        GA.AttaNpc((int)Envir.树林, "0", 0);
                    }
                    if (Setting.GetBool("isYe2"))
                    {
                        GA.AttaNpc((int)Envir.风景区, "1", 0);
                        GA.AttaNpc((int)Envir.树林, "1", 0);
                    }
                }
                List<ZBRare> list2 = new List<ZBRare>();
                if (Setting.GetBool("isSGray"))
                {
                    list2.Add(ZBRare.灰色);
                    //GA.SellZB(ZBType.装备, ZBRare.灰色);
                }
                if (Setting.GetBool("isSWhite"))
                {
                    list2.Add(ZBRare.白色);
                    //GA.SellZB(ZBType.装备, ZBRare.白色);
                }
                if (Setting.GetBool("isSGreen"))
                {
                    list2.Add(ZBRare.绿色);
                    //GA.SellZB(ZBType.装备, ZBRare.绿色);
                }
                if (Setting.GetBool("isSBlue"))
                {
                    list2.Add(ZBRare.蓝色);
                    //GA.SellZB(ZBType.装备, ZBRare.绿色);
                }
                if (list2.Count > 0)
                {
                    GA.SellZB(ZBType.装备, list2);
                }
                #endregion

                /*跑城市*/
                string text = GAClient.DownloadString(GA.ROOT_URL + "/map?t=6&ts=" + Util.GetTime());
                string gone = GARegex.GetString(text, "{fw:[", "]}");
                string[] arrgo = gone.Split(',');
                int cid = UserInfo.Me;
                int gocid = 0;
                int total = 0;

                List<object> list = City.GetCityPoint(cid);
                DataTable dtt = City.GetCityPoint(Convert.ToInt32(list[0]), Convert.ToInt32(list[1]), arrgo);

                if (dtt.Rows.Count == 0)
                {
                    AddMessage("地图已经全部跑完，谢谢使用此功能。");
                    break;
                }
                string[] arrmap = Setting.GetString("map").Split(',');
                //选择下一个城市
                int goindex = -1;
                for (int i = 0; i < dtt.Rows.Count; i++)
                {
                    for (int j = 0; j < arrmap.Length; j++)
                    {
                        string cidd = dtt.Rows[i]["cid"].ToString();
                        if (cidd == arrmap[j])
                        {
                            goindex = i;
                            break;
                        }
                    }
                    if (goindex != -1)
                    {
                        break;
                    }
                }
                //if (goindex==-1)
                //{
                //    goindex = 0;
                //}


                List<object> list3 = City.GetCityPoint(City.GetCityID(UserInfo.Home));//老家的坐标
                int ax, ay, bx, by;
                int.TryParse(list3[0] + "", out ax);
                int.TryParse(list3[1] + "", out ay);
                int.TryParse(dtt.Rows[goindex]["x"] + "", out bx);
                int.TryParse(dtt.Rows[goindex]["y"] + "", out by);

                int total2 = 0;
                total2 = (ax - bx) * (ax - bx) + (ay - by) * (ay - by);

                if (Convert.ToInt32(dtt.Rows[goindex]["total"]) > total2)
                {
                    AddMessage("目标城市与定居地[" + UserInfo.Home + "]距离更近，传送至定居地。");
                    gocid = Convert.ToInt32(dtt.Rows[goindex]["cid"]);
                    total = total2;

                    GA.GoHome();
                }
                else
                {
                    gocid = Convert.ToInt32(dtt.Rows[goindex]["cid"]);
                    total = Convert.ToInt32(dtt.Rows[goindex]["total"]);
                }

                int time = GA.MoveTo(gocid, User.Me);
                if (time > 0)
                {
                    this.SetTimes3(time);
                    //Monitor.Exit(GA.lockvar);
                    this.SetTimerState3(true);
                    AddMessage("已经到达【" + City.GetCity(gocid) + "】。");

                    while (true)
                    {
                        string url = GA.ROOT_URL + "/flers?pid=" + Setting.GetInt("pid") + "&ts=" + Util.GetTime();
                        string text2 = GAClient.DownloadString(url);
                        //MaskMap = [13,1,23,5,3,2,11,6,7,4,9,22,33,19,34,35,36,38,21,66,24,26,32,37,20,8,18,16,10,12,17,25,27,62,64,65];
                        //获得map地址
                        string arrshowcity = GARegex.GetString(text2, "MaskMap = [", "];");
                        //MaskMap = [9,11,10,2,12,18,3,4,5,16];
                        if (!string.IsNullOrEmpty(arrshowcity))
                        {
                            AddMessage("已经获取最新坐标。");
                            Setting.Set("map", arrshowcity);
                            break;
                        }
                        else
                        {
                            AddMessage("没有获取到最新的地图坐标，下次目标可能不是最近地点。");
                            Setting.SetInt("pid", 1);
                            continue;
                        }
                    }
                    UserInfo.Me = gocid;

                }
                else
                {
                    AddMessage("出发错误！！！");
                }
            }
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            int num = 0;

            int.TryParse(this.txtAllTime.Tag + "", out num);
            if (lvyoutime > 10 * 60)
            {
                //starttime = 0;
                //GA.GetJJStatus();
                string text = GA.GetUserStatus();
                AddMessage(GARegex.DelReturn(GARegex.DelHtml(text)) + "！剩余时间：" + Util.GetTime(num));
                lvyoutime = 0;
            }

            if (num > 0)
            {
                num--;
                //this.SetTimes3(num);
                //this.SetTimerState3(true);
                this.SetAutoStartTimer3(num);
                lvyoutime++;
                numtime = num;
            }
            else if (num == 0)
            {
                this.txtAllTime.Text = "操作进行中...";
                this.txtAllTime.Tag = "-999";
                if (tGAAuto != null && tGAAuto.ThreadState == (ThreadState.Suspended | ThreadState.Background))
                {
                    tGAAuto.Resume();
                    this.SetTimerState3(false);
                }
            }
        }

        private void btnLxEnd_Click(object sender, EventArgs e)
        {
            tGAAuto = null;
            this.timerMap.Stop();
            this.btnLxStart.Enabled = true;
            this.btnLxEnd.Enabled = false;
        }

        private void 关于AToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            frmAbout about = new frmAbout();
            about.ShowDialog();
        }

        private void 手动ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tGATemp = new Thread(new ThreadStart(delegate()
            {
                GA.Garden();
            }));
            tGATemp.IsBackground = true;
            tGATemp.Start();
        }

        private void 退出EToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void btnJineng_Click(object sender, EventArgs e)
        {
            int lymin = (int)this.numlymin.Value;
            int lvmax = (int)this.numlymax.Value;
            int swmin = (int)this.numswmin.Value;
            int swmax = (int)this.numswmax.Value;
            bool bly = this.chkStartly.Checked;
            bool bsw = this.chkStartsw.Checked;

            tGAJineng = new Thread(new ThreadStart(delegate()
            {
                //while (true)
                //{
                //    Lvyou();
                //}

                #region 读取已经有的旅游信息

                GAPosition.Building(9);
                Thread.Sleep(500);
                GAPosition.Building(9, "report");
                Thread.Sleep(500);

                string text = "";
                int maxpage = 1;
                int index = 1;
                /*获取所有的已发现的报告物*/
                while (text == "" || index <= maxpage)
                {
                    text = GAPosition.Building(9, "report", "s=1&page=" + index);
                    maxpage = GARegex.GetInt(text, "<a href='#' u='/building9?action=report&s=1&pageId=", @"' class='b'></a>
			</div>");



                    //<div class='zb_i'><h3>(?<name>[^<]+?)</h3><p>所在城市：(?<cname>[^<]+?)</p><p>百科类型：(?<type>[^<]+?)</p>(<p class='s15'>需要技能：\[ (?<jineng>[\s\S]*?) \] (?<rank>[\d]+)</p>)?<p class='s15'>冒险经验 \+ (?<num>[\d]+?)</p>




                    MessageBox.Show(maxpage.ToString());
                    break;



                    index++;
                }






                int p = 0;

                #endregion


            }));
            tGAJineng.IsBackground = true;
            tGAJineng.Start();
        }

        int fxtime;
        private void timer4_Tick(object sender, EventArgs e)
        {
            int num = 0;

            int.TryParse(this.textBox2.Tag + "", out num);
            if (fxtime > 10 * 60)
            {
                //starttime = 0;
                //GA.GetJJStatus();
                string text = GA.GetUserStatus();
                if (text.IndexOf("探宝") == -1)
                {
                    AddMessage("状态异常，可能被终止。");
                    num = 0;
                }
                else
                {
                    AddMessage(GARegex.DelReturn(GARegex.DelHtml(text)) + "！剩余时间：" + Util.GetTime(num));
                }
                fxtime = 0;
            }

            if (num > 0)
            {
                num--;
                this.SetTimes4(num);
                this.SetTimerState4(true);
                //this.SetAutoStartTimer3(num);
                fxtime++;
                numtime = num;
            }
            else if (num == 0)
            {
                this.textBox2.Text = "操作进行中...";
                this.textBox2.Tag = "-999";
                if (tGASearchFor != null && tGASearchFor.ThreadState == (ThreadState.Suspended | ThreadState.Background))
                {
                    tGASearchFor.Resume();
                    this.SetTimerState4(false);
                }
            }
        }

        private void SetTimerState4(bool status)
        {
            this.Invoke(new DelInvoke(delegate()
            {
                if (status)
                {
                    this.timerSearchFor.Start();
                    if (tGASearchFor != null)
                    {
                        tGASearchFor.Suspend();
                    }
                }
                else
                {
                    this.timerSearchFor.Stop();
                }
            }));
        }

        private void SetTimes4(int num)
        {
            this.txtAllTime.Invoke(new DelInvoke(delegate()
            {
                this.textBox2.Text = Util.GetTime(num);
                this.textBox2.Tag = num;
            }));
        }

        private void btnSearchFor_Click(object sender, EventArgs e)
        {
            string name = this.txtSearchFor.Text;
            int envirid;

            int.TryParse(this.cboEnvir6.SelectedValue + "", out envirid);
            if (envirid == 0)
            {
                MessageBox.Show("请输入探宝的名称。");
                return;
            }
            if (name == "")
            {
                MessageBox.Show("请选择场景。"); return;
            }

            ini.WriteInteger("jineng", "SearchForID", envirid);
            ini.WriteString("jineng", "SearchForName", name);
            this.btnSearchFor.Enabled = false;
            tGASearchFor = new Thread(delegate()
            {
                while (true)
                {
                    //this.btnSearchFor.Enabled = false;
                    int t = ShowStatus(tGASearchFor);
                    if (t > 0)
                    {
                        AddMessage("剩余操作时间：" + Util.GetTime(t));
                        SetTimes4(t);
                        SetTimerState4(true);

                    }
                    GA.GoCity(UserInfo.Me);
                    GA.HaveRest();
                    GAPosition.environ();
                    string text = GAPosition.Envir(envirid);
                    AddMessage("已经进入场景【" + Enum.GetName(typeof(Envir), envirid) + "】。");
                    //<a href='#' u='/findf?oid=1010' class='xb s13'><img src='/sys/i/f/8/879.jpg' class='pic' />普救寺</a>

                    int oid = GARegex.GetInt(text, "<div class='zb_i'><h3>" + name + "</h3><*>\" ><a href='#' u='/findf?oid=", "' class='xb <*>'><img src='<*>' class='pic' />" + name + "</a>");
                    if (oid == 0)
                    {
                        AddMessage("没有找到场景【" + name + "】。");
                        break;
                    }
                    AddMessage("找到[" + name + "]准备探宝。");
                    string text2 = GAClient.DownloadString(GA.ROOT_URL + "/findf?oid=" + oid + "&ts=" + Util.GetTime());

                    //s="3535"
                    int time = GARegex.GetInt(text2, "s=\"", "\"");
                    Thread.Sleep(1000);
                    NameValueCollection data = new NameValueCollection();
                    data.Add("mt", "-1");
                    data.Add("mode", "start");
                    //mt=-1&mode=start&
                    string ttt = GAClient.ClientUrl(GA.ROOT_URL + "/findf?oid=" + oid + "&ts=" + Util.GetTime(), data);
                    string alert = GA.GetAlert(ttt);
                    if (string.IsNullOrEmpty(alert))
                    {
                        continue;
                    }
                    else
                    {
                        AddMessage(alert);
                        break;
                    }
                }

                this.Invoke(new DelInvoke(delegate()
                {
                    this.btnSearchFor.Enabled = true;
                }));
            });
            tGASearchFor.IsBackground = true;
            tGASearchFor.Start();
        }

        private void btnSearchForClose_Click(object sender, EventArgs e)
        {
            if (tGASearchFor != null)
            {
                if (tGASearchFor.ThreadState == (ThreadState.Background | ThreadState.Suspended))
                {
                    tGASearchFor.Resume();
                }
                tGASearchFor.Abort();
                this.btnSearchFor.Enabled = true;
            }
            this.timerSearchFor.Stop();
        }


        //查看当前是否是可操作的。
        private int ShowStatus(Thread thread)
        {
            string text = GA.GetUserStatus();
            string position = GARegex.DelHtml(text);
            AddMessage(position);
            if (text.IndexOf("停留在") > 0)
            {

            }
            else
            {
                int tt = GARegex.GetInt(text, " s='", "' ");

                return tt;
            }
            return 0;
        }

        //private void dataGridView2_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        //{
        //    this.dataGridView2.Rows[e.RowIndex].Cells[0].Value = e.RowCount;
        //    DataGridViewComboBoxCell cell = this.dataGridView2.Rows[e.RowIndex].Cells[1] as DataGridViewComboBoxCell;
        //    //cell.Items.Add(new CboItem(1, "长安"));
        //    cell.DataSource = City.dtcity;
        //    cell.DisplayMember = "cname";
        //    cell.ValueMember = "cid";


        //}
        //private void button1_Click(object sender, EventArgs e)
        //{
        //    MessageBox.Show((this.dataGridView2.Rows[0].Cells[1] as DataGridViewComboBoxCell).Value.ToString());
        //}

        private void button2_Click_2(object sender, EventArgs e)
        {

        }


    }

}